import api from './request'
import type { ApiResponse } from '@/types'

// 聊天消息类型
export interface ChatMessage {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: string
  username?: string
  avatar?: string
}

// 会话类型
export interface ChatSession {
  id: string
  title: string
  createdAt: string
  updatedAt: string
  lastMessageTime?: string
  messageCount?: number
}

// 聊天历史响应
export interface ChatHistoryResponse {
  sessions: ChatSession[]
  total: number
}

// 单个会话消息响应
export interface ChatMessagesResponse {
  messages: ChatMessage[]
  total: number
  sessionInfo: ChatSession
}

// 辅助函数，用于获取请求头
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'token': token || ''
    // 'Content-Type' 由axios根据请求体自动设置
  }
}

// 创建新会话
export async function createChatSession(title: string, userId: string | number) {
  // 强制 userId 转为 number 类型，后端要求 Integer
  console.log('id:', userId)
  const userIdInt = typeof userId === 'string' ? parseInt(userId, 10) : userId;
  console.log('创建会话请求，标题:', title, 'userId:', userIdInt)
  try {
    const response = await api.post('/ai/sessions', { title, userId: userIdInt }, { 
      headers: getAuthHeaders() 
    })
    console.log('创建会话响应:', response)
    return response
  } catch (error) {
    console.error('创建会话请求失败:', error)
    throw error
  }
}

// 获取聊天历史（会话列表）
export async function getChatHistory(userId?: number, page = 1, size = 20) {
  console.log('获取会话历史请求，userId:', userId, 'page:', page, 'size:', size)
  try {
    const response = await api.get('/ai/sessions', { 
      params: { userId, page, size },
      headers: getAuthHeaders() 
    })
    console.log('获取会话历史响应:', response)
    return response
  } catch (error) {
    console.error('获取会话历史请求失败:', error)
    throw error
  }
}

// 获取指定会话的消息
export async function getChatMessages(sessionId: string, userId?: number, page = 1, size = 50) {
  console.log('获取会话消息请求，sessionId:', sessionId, 'userId:', userId, 'page:', page, 'size:', size)
  try {
    const response = await api.get(`/ai/sessions/${sessionId}/messages`, { 
      params: { userId, page, size },
      headers: getAuthHeaders() 
    })
    console.log('获取会话消息响应:', response)
    return response
  } catch (error) {
    console.error('获取会话消息请求失败:', error)
    throw error
  }
}

// 发送消息（非流式响应）
export const sendMessage = async (
  prompt: string,
  sessionId: string
) => {
  console.log('发送消息请求，prompt:', prompt, 'sessionId:', sessionId)
  // 使用 URLSearchParams 来匹配后端 @RequestParam
  const params = new URLSearchParams()
  params.append('prompt', prompt)
  params.append('sessionId', sessionId)

  console.log('发送消息参数:', params.toString())
  return api.post('/ai/chat', params, {
    headers: {
      ...getAuthHeaders(),
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

// 更新会话标题
export async function updateSessionTitle(sessionId: string, title: string) {
  // 移除 TypeScript 泛型类型约束，让其返回原始响应
  return api.put(`/ai/sessions/${sessionId}`, { title }, { 
    headers: getAuthHeaders() 
  })
}

// 删除会话
export async function deleteChatSession(sessionId: string) {
  // 移除 TypeScript 泛型类型约束，让其返回原始响应
  return api.delete(`/ai/sessions/${sessionId}`, { 
    headers: getAuthHeaders() 
  })
}

// AI生成日程计划
export async function aiGenerateSchedule({
  date,
  userId,
  semesterStartDate,
  sessionId
}: {
  date: string,
  userId: number,
  semesterStartDate?: string,
  sessionId?: string
}) {
  const params = new URLSearchParams()
  params.append('日期', date)
  params.append('用户id', String(userId))
  if (semesterStartDate) params.append('学期开始日期', semesterStartDate)
  if (sessionId) params.append('sessionId', sessionId)
  return api.post('/aiSchedule/AIGenerate', params, {
    headers: {
      ...getAuthHeaders(),
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

//AI生成课程学习计划
export async function aiGenerateCourse({
    userId, semesterStartDate, sessionId}:{
  userId: string, semesterStartDate?: string, sessionId?: string
}){
  const params = new URLSearchParams()
  params.append('用户id', String(userId))
  if(semesterStartDate) params.append('学期开始日期', semesterStartDate)
  if(sessionId) params.append('sessionId', sessionId)
  return api.post('/aiAdvice/aiGenerate', params, {
    headers: {
      ...getAuthHeaders(),
      'Content-Type' : 'application/x-www-form-urlencoded'
    }
  })
}